<?php

namespace frontend\controllers;
use common\components\Myhelpers;
use common\models\Address;
use yii;

class AddressController extends FController
{
    public function init()
    {
        parent::init();
        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }
    }

    /**
     * ajax添加收货地址
     */
    public function actionAdd(){
        $user_id = Yii::$app->user->id;
        do{
            $rs = array('errNo' => 0, 'msg' => '添加成功');
            foreach( $_POST as $k=>$v ){
                $_POST[$k] = Myhelpers::RemoveXSS($v);
            }

            //判断此用户是否有默认收货地址
            $has_default = Address::find()->where('user_id=:user_id AND is_default=1', [':user_id'=>$user_id])->one();

            $address = new Address();
            $address->user_id = $user_id;
            $address->name = $_POST['name'];
            $address->province = $_POST['province'];
            $address->city = $_POST['city'];
            $address->district = $_POST['district'];
            $address->address_detail = $_POST['address_detail'];
            $address->phone = $_POST['phone'];
            $address->tel = $_POST['tel'];
            $address->zip_code = $_POST['zip_code'];
            $address->is_default = $has_default?2:1;
            $address->is_show = 1;
            $address->create_time = date('Y-m-d H:i:s');

            if( !$address->save(false) ){
                $rs = array('errNo' => 1, 'msg' => '添加失败');
            }
        }while(false);

        exit(json_encode($rs));
    }

    public function actionUpdate(){
        //增加数据
        $add_save_data = Yii::$app->request->post('save_update');
        $post_data = json_decode($add_save_data,true);

        foreach( $post_data as $k=>$v ){
            $post_data[$k] = Myhelpers::RemoveXSS($v);
        }
        
        if( $post_data ){
            if(!$post_data[1] || !$post_data[2] || strlen($post_data[2])!=11 || !$post_data[5] || !$post_data[6] || !$post_data[7] || !$post_data[8] || !$post_data[9]){
                return 0;
            }
        }
        if($post_data[1]){
            $data['user_id'] = Yii::$app->user->id;
            $data['name'] = $post_data[1];
            $data['province'] = $post_data[6];
            $data['city'] = $post_data[7];
            $data['district'] = $post_data[8];
            $data['address_detail'] = $post_data[5];
            $data['phone'] = $post_data[2];
            $data['tel'] = $post_data[3];
            $data['zip_code'] = $post_data[4];

            if($post_data[0] == 0){
                $save_res = Yii::$app->db->createCommand()
                        ->update('address', $data, 
                            'id = '.$post_data[9])
                        ->execute();
            }
            
            return $save_res = $save_res?$save_res:0;
        }
    }

}
